// https://www.lintcode.com/problem/merge-two-sorted-lists/

/**
 * Definition for ListNode
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param l1: ListNode l1 is the head of the linked list
     * @param l2: ListNode l2 is the head of the linked list
     * @return: ListNode head of linked list
     */
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        // write your code here
        ListNode head = null, tail = null;
        while ((l1 != null) && (l2 != null)) {
            ListNode tmp = null;
            if (l1.val < l2.val) {
                tmp = l1;
                l1 = l1.next;
            }
            else {
                tmp = l2;
                l2 = l2.next;
            }
            if (null == head) {
                head = tmp;
                tail = tmp;
            }
            else {
                tail.next = tmp;
                tail = tail.next;
            }
            tail.next = null;
        }
        if ((l1 != null) || (l2 != null)) {
            ListNode tmp = null;
            if (l1 != null) {
                tmp = l1;
            }
            else {
                tmp = l2;
            }
            if (null == head) {
                head = tmp;
            }
            else {
                tail.next = tmp;
            }
        }
        return head;
    }
}